package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysUserDao;
import com.leenmvc.core.security.entity.core.SysRoleUser;
import com.leenmvc.core.security.entity.core.SysUser;
import com.leenmvc.core.utils.dictionary.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysRoleUserService extends BaseService<SysRoleUser> {

    @Autowired
    private SysUserDao sysUserDao;

    @TransactionMulti
    public <T> boolean insert(T t) {

        if(!super.insert(t)) {
            throw new BusinessException("INSERT_FAIL", SysRoleUser.class);
        };

        SysRoleUser sysRoleUser = (SysRoleUser) t;
        String superAdminId = Dict.value("SYSTEM", "SUPER_USER_ID");
        if(sysRoleUser.getRoleId().toString().equals(superAdminId)) {
            SysUser sysUser = sysUserDao.get(sysRoleUser.getUserId());
            sysUser.setSuperAdmin(1);
            if(!sysUserDao.update(sysUser)) {
                throw new BusinessException("UPDATE_FAIL", SysUser.class);
            };
        }
        return true;
    }

    @Override
    public int deleteByIds(Object[] ids) {
        String superAdminId = Dict.value("SYSTEM", "SUPER_USER_ID");
        for (Object id : ids) {
            SysRoleUser roleUser = get(id);
            if(roleUser.getRoleId().toString().equals(superAdminId)){
                Long userId = roleUser.getUserId();
                SysUser sysUser = sysUserDao.get(userId);
                sysUser.setSuperAdmin(0);
                sysUserDao.update(sysUser);
            }
        }
        return super.deleteByIds(ids);
    }
}
